/**
 * @Author:marina
 * @Date: 2025-02-12 09:55:24 
 * @Description:根据表格的数据长度生成表格长度
 */

<script setup lang="ts" name="flexWidth">
import { store } from '../stores/store'
interface TableDataItem {
    date?: string;
    name?: string;
    address?: string;
    [key: string]: any;
}

const CounterStore = store() as { tableData: TableDataItem[] };

function getColumnWidth(prop:string) {
    const minWidth = 80; // 最小宽度
    const padding = 16; // 列内边距

    const contentWidths = CounterStore.tableData.map((item) => {
        const value = item[prop] ? String(item[prop]) : "";
        const textWidth = getTextWidth(value);
        return textWidth + padding;
    });

    const maxWidth = Math.max(...contentWidths);

    return Math.max(minWidth, maxWidth);
}
function getTextWidth(text:any) {
    const span = document.createElement("span");
    span.style.visibility = "hidden";
    span.style.position = "absolute";
    span.style.top = "-9999px";
    span.style.whiteSpace = "nowrap";
    span.innerText = text;
    document.body.appendChild(span);
    const width = span.offsetWidth + 5;
    document.body.removeChild(span);
    return width;
}
</script>

<template>
    <el-table
        :data="CounterStore.tableData"
        stripe
        border
    >
        <!-- v-fit-columns -->
        <el-table-column
            prop="date"
            label="Date"
        />
        <el-table-column
            prop="name"
            label="Name"
            resizeable
        />
        <!-- class-name="leave-alone" -->
        <el-table-column
            prop="address"
            label="Address"
            :min-width="getColumnWidth('address')"
        />
    </el-table>
</template>

<style scoped lang="less">
.el-table {
    width: 800px;
    margin-left: 100px;
}
</style>